#! /bin/sh

self=$0

# file mode mask, do not set `go' write permission
umask 022

on_exit() { echo "error: '$self' exited outside the expected code flow"; }
trap on_exit EXIT
trap ":" INT QUIT TSTP	# <-- ignore ctrl+c

# translate LF to CR+LF to avoid staircase effect
stty onlcr 0>&1

source /lib/lsb/init-functions

runlevel=$RUNLEVEL
[ -n "$1" ] || runlevel=$1
[ -n "$runlevel" ] || echo_exit "Usage: $self <runlevel>"

prelevel=$PRELEVEL
[ -n "$prelevel" ] || prelevel=N
export runlevel prelevel

[ -f "/etc/default/rc" ] && source /etc/default/rc

# check $prelevel and stop corresponding service
# we stop all services started by the previous runlevel,
# and killed in this level
if [ "$prelevel" != "N" ]; then
	for x in $(ls -v /etc/rc$runlevel.d/K* 2>/dev/null); do
		# Maybe we should check previous and sys-init started
		# services and then stop its ?
		# FIXME
		$x stop
	done
fi

[ -d /etc/rc$runlevel.d ] || echo_exit "/etc/rc$runlevel.d does not exists."

for x in $(ls -v /etc/rc$runlevel.d/S* 2>/dev/null); do
	if [ "$prelevel" != "N" ]; then
		suffix=${x##*/S[0-9][0-9]}
		stop=/etc/rc$runlevel.d/K[0-9][0-9]$suffix
		prevstart=/etc/rc$prelevel.d/S[0-9][0-9]$suffix

		[ -f $prefstart -a ! -f $stop ] && continue
	fi

	action=start
	[ -z "${x#[06]}" ] && action=stop
	$x $action || log_err "$x $action fail(status=$?)"
done

trap - EXIT

exit 0
